package com.web.webstart.base.util;

import com.web.exiaodao.business.constant.JConstant;
import com.web.webstart.base.security.XaUserDetails;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class XaUtil {

	/**
	 * 判断对象是否Empty(null或元素为0)<br>
	 * 实用于对如下对象做判断:String Collection及其子类 Map及其子类
	 * 
	 * @param pObj
	 *            待检查对象
	 * @return boolean 返回的布尔值
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isEmpty(Object pObj) {
		if (pObj == null)
			return true;
		if (pObj == "")
			return true;
		if (pObj instanceof String) {
			if (((String) pObj).trim().length() == 0) {
				return true;
			}
		} else if (pObj instanceof Collection) {
			if (((Collection) pObj).size() == 0) {
				return true;
			}
		} else if (pObj instanceof Map) {
			if (((Map) pObj).size() == 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断对象是否为NotEmpty(!null或元素>0)<br>
	 * 实用于对如下对象做判断:String Collection及其子类 Map及其子类
	 * 
	 * @param pObj
	 *            待检查对象
	 * @return boolean 返回的布尔值
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isNotEmpty(Object pObj) {
		if (pObj == null)
			return false;
		if (pObj == "")
			return false;
		if (pObj instanceof String) {
			if (((String) pObj).trim().length() == 0) {
				return false;
			}
		} else if (pObj instanceof Collection) {
			if (((Collection) pObj).size() == 0) {
				return false;
			}
		} else if (pObj instanceof Map) {
			if (((Map) pObj).size() == 0) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Boolean 使用前要进行判断,否则空指针异常
	 * 可以参加 {@link org.apache.commons.lang3.BooleanUtils}
	 * @param bool
	 * @return
	 */
	public static boolean getBool(Boolean bool) {
		if (bool == null) {
			return false;
		}
		return bool;
	}

	public static String getNutNullStr(Object o, String  defaultValue) {
		if (isEmpty(o)) {
			return defaultValue;
		}
		return o.toString();
	}

	public static Long getNutNullLong(Object o, Long  defaultValue) {
		if (isEmpty(o)) {
			return defaultValue;
		}
		return Long.parseLong(o.toString());
	}

	public static double getNutNullDouble(Object o, double  defaultValue) {
		if (isEmpty(o)) {
			return defaultValue;
		}
		return Double.parseDouble(o.toString());
	}

	public static String getNutNullStr(Object o) {
		return getNutNullStr(o, "");
	}


	//获取子串,str可以是null
	public static String getSubStr(String str, int maxLength) {
		return XaUtil.isEmpty(str) ? "" : str.length() > maxLength ? str.substring(0, maxLength) : str;
	}

	/**
	 * 数据格式化.
	 * 
	 * @param pattern
	 *            the pattern
	 * //@param i
	 *            the i
	 * @return the string
	 */
	public static String codeFormat(String pattern, Object value) {
		DecimalFormat df = new DecimalFormat(pattern);
		return df.format(value);
	}

	/**
	 * 格式化金额.
	 * 
	 * @param value
	 *            the value
	 * @return the string
	 */
	public static String formatCurrency2String(Long value) {
		if (value == null || "0".equals(String.valueOf(value))) {
			return "0.00";
		}
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(value / 100.00);
	}

	/**
	 * 格式化金额.
	 * 
	 * @param priceFormat
	 *            the price format
	 * @return the long
	 */
	public static Long formatCurrency2Long(String priceFormat) {
		BigDecimal bg = new BigDecimal(priceFormat);
		Long price = bg.multiply(new BigDecimal(100)).longValue();
		return price;
	}


    /**
     * 获取已登录 cms 用户名
     *
     */
    public static String getCmsLoginedUserName() {
        Object userDetails = SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        String userName = "";
        if (userDetails instanceof String) {
            userName = (String) userDetails;
        } else if (userDetails instanceof XaUserDetails) {
            userName = ((XaUserDetails) userDetails).getUsername();
        }
        return userName;
    }


    /**
     * 去除html标签
     * @param htmlStr
     * @return
     */
    public static String delHTMLTag(String htmlStr){ 
        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 
        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 
        String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式 
        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE); 
        Matcher m_script=p_script.matcher(htmlStr); 
        htmlStr=m_script.replaceAll(""); //过滤script标签 
        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE); 
        Matcher m_style=p_style.matcher(htmlStr); 
        htmlStr=m_style.replaceAll(""); //过滤style标签 
        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); 
        Matcher m_html=p_html.matcher(htmlStr); 
        htmlStr=m_html.replaceAll(""); //过滤html标签 
        return htmlStr.trim(); //返回文本字符串 
    }


	 /**
		 * 将xml字符串转化为实体对象
		 * @param <T>
		 * @param xml
		 * @param clazz
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public static<T> T xml2bean(String xml,Class<T>clazz){
			T t=null;
			try{
				JAXBContext context = JAXBContext.newInstance(clazz);
		        Unmarshaller unmarshaller = context.createUnmarshaller();
		        t=(T)unmarshaller.unmarshal(new StringReader(xml));
		        
			}catch (Exception e){
				throw new RuntimeException(e.getMessage(),e);
			}
			return t;
		}
		

	/**
	 * 生成一定规则的token，32位随机字符串
	 * 规则1：生成的字符串中字符位置遇3的倍数时
	 * @return
	 */
	public static String generateToken(){
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 32; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        //对生成的随机字符串做处理符合一定的规则
        
		return "";
	}
	
	/**
	 * 获取字符的键盘值
	 * @param s
	 * @return
	 */
	private static Integer getKeyValue(char s){
		Integer result = 0;
		switch(s){
			case 'A' : result = 65; break;
			case 'B' : result = 66; break;
			case 'C' : result = 67; break;
			case 'D' : result = 68; break;
			case 'E' : result = 69; break;
			case 'F' : result = 70; break;
			case 'G' : result = 71; break;
			case 'H' : result = 72; break;
			case 'I' : result = 73; break;
			case 'J' : result = 74; break;
			case 'K' : result = 75; break;
			case 'L' : result = 76; break;
			case 'M' : result = 77; break;
			case 'N' : result = 78; break;
			case 'O' : result = 79; break;
			case 'P' : result = 80; break;
			case 'Q' : result = 81; break;
			case 'R' : result = 82; break;
			case 'S' : result = 83; break;
			case 'T' : result = 84; break;
			case 'U' : result = 85; break;
			case 'V' : result = 86; break;
			case 'W' : result = 87; break;
			case 'X' : result = 88; break;
			case 'Y' : result = 89; break;
			case 'Z' : result = 90; break;
			case 'a' : result = 97; break;
			case 'b' : result = 98; break;
			case 'c' : result = 99; break;
			case 'd' : result = 100; break;
			case 'e' : result = 101; break;
			case 'f' : result = 102; break;
			case 'g' : result = 103; break;
			case 'h' : result = 104; break;
			case 'i' : result = 105; break;
			case 'j' : result = 106; break;
			case 'k' : result = 107; break;
			case 'l' : result = 108; break;
			case 'm' : result = 109; break;
			case 'n' : result = 110; break;
			case 'o' : result = 111; break;
			case 'p' : result = 112; break;
			case 'q' : result = 113; break;
			case 'r' : result = 114; break;
			case 's' : result = 115; break;
			case 't' : result = 116; break;
			case 'u' : result = 117; break;
			case 'v' : result = 118; break;
			case 'w' : result = 119; break;
			case 'x' : result = 120; break;
			case 'y' : result = 121; break;
			case 'z' : result = 122; break;
			case '0' : result = 48; break;
			case '1' : result = 49; break;
			case '2' : result = 50; break;
			case '3' : result = 51; break;
			case '4' : result = 52; break;
			case '5' : result = 53; break;
			case '6' : result = 54; break;
			case '7' : result = 55; break;
			case '8' : result = 56; break;
			case '9' : result = 57; break;
			default : result = 0;
		}
		return result;
	}

	/**
     * @author duandazhi
     * @date 2016/12/6 下午3:03
     * @param str 待分割的字符串;可以为空
     * @param separatorChars 分割符号;可以为空;默认英文逗号,
     * @return
     */
    public static Long[] splitLong(String str, String separatorChars) {
        if (isEmpty(str)) {
            return null;
        }
        List<String> list = Arrays.asList(StringUtils.split(str,
                XaUtil.isEmpty(separatorChars) ? JConstant.SYMBOL_DOT : separatorChars));
        Long[] longs = new Long[list.size()];
        int kk = 0;
        for (String ss : list) {
            longs[kk] = Long.parseLong(ss);
            kk++;
        }
        return longs;
    }

	/**
	 * 防止sql注入
	 * System.out.print("防SQL注入:"+StringEscapeUtils.escapeSql("1' or '1'='1"));;
	 * @param str
	 * @return
	 */
	public static String Sql(String str) {
    	return " '" + StringEscapeUtils.escapeSql(str) + "' ";
	}

	public static void main(String[] args) {
		//System.out.println(Sql("1' or '1'='1"));
//		String ss = "{\"status\":1,\"result\":\"修改资源成功\"}";
//		System.out.println(StringEscapeUtils.unescapeJavaScript(ss));
	}


	public static  String dealMobileStr(String mobileOldStr) {
		if (XaUtil.isEmpty(mobileOldStr)) {
			return null;
		}
		String str = mobileOldStr.replace("-", "").trim().replace(" ","");
		if (str.length() > 11) {
			str = str.substring(11);
		}
		return str;
	}
}